package com.jinlia.show.modules.base.system.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinlia.show.common.core.utils.UserInfoUtils;
import com.jinlia.show.modules.base.constant.EnableStatusEnum;
import com.jinlia.show.modules.base.constant.OrderPayStatusEnum;
import com.jinlia.show.modules.base.constant.OrderStatusEnum;
import com.jinlia.show.modules.base.system.entity.*;
import com.jinlia.show.modules.base.system.mapper.OrderMapper;
import com.jinlia.show.modules.base.model.form.OrderForm;
import com.jinlia.show.modules.base.model.po.OrderPO;
import com.jinlia.show.modules.base.model.po.OrderItemPO;
import com.jinlia.show.modules.base.model.query.OrderQuery;
import com.jinlia.show.modules.base.wxapp.entity.User;
import com.jinlia.show.modules.base.wxapp.service.UserMapperService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrderMapperService extends ServiceImpl<OrderMapper, Order> {
    @Autowired
    OrderItemMapperService orderItemMapperService;
    @Autowired
    GoodsMapperService goodsMapperService;
    @Autowired
    IdGeneratorMapperService idGeneratorMapperService;
    @Autowired
    DeliveryOrderMapperService deliveryOrderMapperService;
    @Autowired
    UserMapperService userMapperService;
    @Autowired
    MemberCardMapperService memberCardMapperService;

    //
    public Page<OrderPO> pageList(OrderQuery orderQuery) {
        //构造查询参数
        Page<OrderPO> page = new Page<>(orderQuery.getCurrent(), orderQuery.getSize());
        Page<OrderPO> sysUserVOPage = this.getBaseMapper().pageListVO(page, orderQuery);
        this.setItems(true, sysUserVOPage.getRecords());
        //填充配送单
        if (orderQuery.isNeedDeliveryOrder() && !CollectionUtils.isEmpty(sysUserVOPage.getRecords())) {
            List<DeliveryOrder> list = deliveryOrderMapperService.lambdaQuery()
                    .in(DeliveryOrder::getOrderId, sysUserVOPage.getRecords().stream().map(OrderPO::getId).collect(Collectors.toSet()))
                    .list();
            Map<Long, DeliveryOrder> collect = list.stream().collect(Collectors.toMap(DeliveryOrder::getOrderId, Function.identity()));
            for (OrderPO record : sysUserVOPage.getRecords()) {//
                if (collect.containsKey(record.getId())) {
                    record.setDeliveryOrder(collect.get(record.getId()));
                }
            }
        }
        return sysUserVOPage;
    }

    private void getGoodsMapByIds(List<OrderPO> records, HashSet<Long> goodsIds) {
        if (CollectionUtils.isEmpty(goodsIds)) {
            return;
        }
        Map<Long, Goods> idMapGoods = goodsMapperService.lambdaQuery()
                .in(Goods::getId, goodsIds)
                .list()
                .stream().collect(Collectors.toMap(Goods::getId, Function.identity()));
        records.forEach(orderEntityVO -> {
            if (!CollectionUtils.isEmpty(orderEntityVO.getItems())) {
                orderEntityVO.getItems().forEach(orderItemEntityVO -> {
                    orderItemEntityVO.setGoods(idMapGoods.get(orderItemEntityVO.getGoodsId()));
                });
            }
        });
    }

    /**
     * 通过购物车下单
     *
     * @param orderForm
     */
    public Order orderByShoppingCar(OrderForm orderForm) {
        if (Objects.isNull(orderForm.getOriginalMoney())) {
            throw new RuntimeException("订单原价不能为null");
        }
        if (Objects.isNull(orderForm.getReceivableMoney())) {
            throw new RuntimeException("订单应收金额不能为null");
        }
        /**
         * 构造订单
         */
        Order order = new Order();
        order.setCompanyId(orderForm.getCompanyId());
        order.setAppId(orderForm.getAppId());
        order.setDeliveryType(orderForm.getDeliveryType());//类型
        order.setRemark(orderForm.getRemark());//订单备注
        order.setOriginalMoney(orderForm.getOriginalMoney());//订单原件
        order.setReceivableMoney(orderForm.getReceivableMoney());//订单应收
        order.setDiscountMoney(orderForm.getDiscountMoney() == null ? BigDecimal.ZERO : orderForm.getDiscountMoney());//折扣金额
        order.setMlMoney(Objects.isNull(orderForm.getMlMoney()) ? BigDecimal.ZERO : orderForm.getMlMoney());//抹零金额
        order.setDeliveryMoney(Objects.isNull(orderForm.getDeliveryMoney()) ? BigDecimal.ZERO : orderForm.getDeliveryMoney());//配送费
        //--------------------------以上为前端出传入的数据----------------------
        order.setOrderStatus(OrderStatusEnum.STEP_0.getValue());
        order.setUserId(UserInfoUtils.getUserId());
        User byIdUser = userMapperService.getById(order.getUserId());
        order.setMemberCardId(byIdUser.getMemberCardId());
        order.setEnableStatus(EnableStatusEnum.ENABLE.getValue());//设置订单状态
        order.setPayStatus(OrderPayStatusEnum.UN_PAY.getValue());//未收款
        order.setReceivedMoney(BigDecimal.ZERO);//已收
        order.setRefundedMoney(BigDecimal.ZERO);//已退
        order.setOrderDate(LocalDate.now());//订单日期
        return order;
    }
    public Order initOrder(Order order) {
        if (order.getOriginalMoney() == null || order.getReceivableMoney() == null) {
            throw new RuntimeException("订单原价和应收金额不能为null");
        }
        if (order.getMlMoney() == null) {
            order.setMlMoney(BigDecimal.ZERO);
        }
        if (order.getDiscountMoney() == null) {
            BigDecimal discountMoney = order.getOriginalMoney().subtract(order.getMlMoney()).subtract(order.getReceivableMoney());
            order.setDiscountMoney(discountMoney);
        }
        order.setDeliveryMoney(Objects.isNull(order.getDeliveryMoney()) ? BigDecimal.ZERO : order.getDeliveryMoney());//配送费
        order = this.initOrderStatus(order);
        return order;
    }
    private Order initOrderStatus(Order order) {
        order.setOrderStatus(OrderStatusEnum.STEP_0.getValue());
        if (order.getUserId() == null && order.getMemberCardId() == null) {
            throw new RuntimeException("会员卡id和用户id不能同时为null");
        }
        if (order.getMemberCardId() != null && order.getUserId() == null) {
            List<User> list = userMapperService.lambdaQuery().eq(User::getMemberCardId, order.getMemberCardId()).list();
            order.setUserId(list.get(0).getId());
        }else if (order.getMemberCardId() == null && order.getUserId() != null){
            User byIdUser = userMapperService.getById(order.getUserId());
            order.setMemberCardId(byIdUser.getMemberCardId());
        }
        order.setEnableStatus(EnableStatusEnum.ENABLE.getValue());//设置订单状态
        order.setPayStatus(OrderPayStatusEnum.UN_PAY.getValue());//未收款
        order.setOrderDate(LocalDate.now());//订单日期
        order.setRefundedMoney(BigDecimal.ZERO); //
        order.setReceivedMoney(BigDecimal.ZERO); //已收
        return order;
    }
    /**
     * 通过id获取PO,并填充信息
     *
     * @param ids
     * @return
     */
    public List<OrderPO> getPOByIds(Long... ids) {
        if (ids.length == 0) {
            return Arrays.asList();
        }
        List<Order> orders = this.listByIds(Arrays.asList(ids));
        List<OrderPO> orderPOS = transToPOs(orders);
        return orderPOS;
    }

    public List<OrderPO> transToPOs(List<Order> orders) {
        List<OrderPO> collect = orders.stream().map(OrderPO::fromEntity).collect(Collectors.toList());
        //填充Item信息
        if (!CollectionUtils.isEmpty(collect)) {
            Long[] longs = collect.stream().map(OrderPO::getId).toArray(Long[]::new);
            Map<Long, List<OrderItemPO>> listVOByOrderId = orderItemMapperService.getListVOByOrderId(longs);
            for (OrderPO record : collect) {//
                record.setItems(listVOByOrderId.get(record.getId()));
            }
        }
        //填充商品goods
        if (!CollectionUtils.isEmpty(collect)) {
            //获取订单上的所有goodsId
            HashSet<Long> goodsIds = new HashSet<>();
            collect.forEach(orderEntityVO -> {
                if (!CollectionUtils.isEmpty(orderEntityVO.getItems())) {
                    goodsIds.addAll(orderEntityVO.getItems().stream().map(OrderItemPO::getGoodsId).collect(Collectors.toSet()));
                }
            });
            getGoodsMapByIds(collect, goodsIds);
        }
        return collect;
    }

    public OrderPO getOrderPO(Long id) {
        OrderPO orderPO = getPOByIds(id).get(0);
        return orderPO;
    }

    public void setItems(Boolean needSetGoods, List<OrderPO> orderPOList) {
        //填充Item信息
        if (CollectionUtils.isEmpty(orderPOList) ){
            return;
        }
        Long[] orderIds = orderPOList.stream().map(OrderPO::getId).toArray(Long[]::new);
        Map<Long, List<OrderItemPO>> listVOByOrderId = orderItemMapperService.getListVOByOrderId(orderIds);
        for (OrderPO record : orderPOList) {//
            record.setItems(CollectionUtils.isEmpty(listVOByOrderId.get(record.getId())) ? Arrays.asList() : listVOByOrderId.get(record.getId()));
        }
        if (needSetGoods) {
            //填充商品goods
            HashSet<Long> goodsIds = new HashSet<>();
            listVOByOrderId.values().forEach(orderEntityVO -> {
                goodsIds.addAll(orderEntityVO.stream().map(OrderItemPO::getGoodsId).collect(Collectors.toSet()));
            });
            if (!CollectionUtils.isEmpty(goodsIds)) {
                getGoodsMapByIds(orderPOList, goodsIds);
            }
        }

    }
}
